// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import VueResource from 'vue-resource'
import App from './App'
import router from './router'
import store from './store'

Vue.use(VueResource)
Vue.http.headers.common['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
Vue.config.productionTip = false
Vue.prototype.$Hub = Vue.prototype.$Hub || new Vue()

store.state.token = [localStorage.getItem('_TOKEN')]

// local api service
Vue.http.interceptors.push((request, next) => {
	if(request.url.indexOf('/api') === 0) {
		request.headers.map.authorization = store.state.token
		next((response) => {
			if(response.url === '/api/login') {
				var token = response.headers.map.authorization
				store.state.token = token

				localStorage.setItem('_TOKEN', token)
			}
			if(response.status === 401) {
				localStorage.removeItem('_TOKEN')
				router.push({
					name: 'Login',
					params: {
						msg: 'You have to login first'
					}
				})
			} else if(response.status === 504) {
				router.push({
					name: 'Login',
					params: {
						msg: 'Timeout'
					}
				})
			}
			return response
		})
	} else {
		next()
	}
})

/* eslint-disable no-new */
new Vue({
	el: '#app',
	store,
	router,
	render: h => h(App)
})
